import { Models } from "../../../common/typings/model";
import KoaRouter from 'koa-router'
import Mysql from "../../../core/Mysql";
import Result from "../../../common/utils/Result";
import httpErrors from '../../../core/HttpException'
import config from '../../../config/config'
import loginSchema from '../../../common/apiValidate/user/login'
import validator from '../../../middlewares/validator'
import bcrypt from "bcryptjs"
import utils from '../../../common/utils/Utils'
import Auth from '../../../middlewares/Auth'
import WxManager from '../../../service/WxManager'
const router = new KoaRouter({
    prefix:'/api/v1/user'
})

router.get('/getUserInfo.do',Auth.verifyToken,async (ctx: Models.Ctx,next:Function)=> {
    let id = ''
    if(ctx.auth){
        id = ctx.auth.uid
    }
    // role 字段，角色，与权限相关
    const res = await Mysql.query(`
        SELECT 
        id,nick_name,email,test,info,role
        FROM 
            user
        where 
            user.id = '${id}'
    `)
    throw new httpErrors.Success(res.results[0])

    
})

/*
 * 登录获取token的接口
 * @param { string } type ,100微信登录，101邮箱登录
 * @param { string } account ,邮箱, type为101时必填
 * @param { string } secret ,密码，type为101时必填
 * @param { string } code ，微信code ，type为100时必填
 * @return { string } token  成功返回token
 */
router.post('/login.do',validator(loginSchema,'body'), async (ctx,next)=> {
    
    let v 
    const query = ctx.request.body
    
    if(query.code !== ctx.session!.code){
        throw new httpErrors.ParameterException('验证码错误')
    }
    let type = Number(query.type)
    let token,user
    switch(type) {
        case config.LoginType.Email: //email登录
            validator(loginSchema)
            let res = await emailLogin(query.email,query.password)
            user = res?.user
            token = res?.token
            break
        case config.LoginType.WeChat: //小程序登录
            // v = await new MiniTokenValidator().validate(ctx)
            // token = await wxLogin(query.code)
            break
        default:
            throw new httpErrors.ParameterException('没有相应的处理函数')
        }
    // await Token.saveToken(token)
    throw new httpErrors.Success({user,token})
})

// /*
//  * 验证token是否通过的接口
//  * @param { string } token
//  * @return { Boolean } true  成功返回true
//  */
// router.post('/verify',async (ctx,next)=> {
//     const v = await new NotEmptyValidator().validate(ctx)
//     const query = ctx.request.body
//     const result = await Auth.verifyToken(query.token)
//     ctx.body = {
//         result
//     }
// })

// /*
//  * 注销登录
//  * @param { string } token
//  * @return { Boolean } true  成功返回true
//  */
// router.post('/cancellation',async (ctx,next)=> {
//     const v = await new NotEmptyValidator().validate(ctx)
//     const query = ctx.request.body
//     const result = await Token.deleteToken(query.token)
//     ctx.body = {
//         success: result
//     }
// })


// // email登录
async function emailLogin(email: string,password: string) {
    let res: Models.Result = await Mysql.query(`
        SELECT 
        id,nick_name,email,test,info,password,role
        FROM 
            user
        where 
            user.email = '${email}'
    `)
    if(!res.error){
        const user = res.results[0]
        const correct = await bcrypt.compareSync(password,user.password)
        if(!correct) {
            throw new httpErrors.ParameterException('密码不正确')
        }
        return {
            token: utils.generateToken(user.id, config.UserLevel.User.toString()),
            user
        }
    }
    
}

// 微信登录
async function wxLogin(code: string) {
    const token= await WxManager.codeToToken(code);
    return token
}

export default router